package yz.cp.back.admin.controller;


import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import yz.cp.back.admin.service.DepartmentManage;
import yz.cp.back.auth.security.SecUser;
import yz.cp.back.auth.security.SecurityUtils;
import yz.cp.back.common.base.BaseController;
import yz.cp.back.common.constant.CommonConstant;
import yz.cp.back.common.res.ApiResult;
import yz.cp.back.common.utils.JacksonUtil;
import yz.cp.back.s.entity.SysDepartment;
import yz.cp.back.s.entity.SysDepartmentHeader;
import yz.cp.back.s.entity.SysUser;
import yz.cp.back.s.service.ISysDepartmentHeaderService;
import yz.cp.back.s.service.ISysDepartmentService;
import yz.cp.back.s.service.ISysRoleDepartmentService;
import yz.cp.back.s.service.ISysUserService;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


/**
 * 部门管理接口
 * @author  xukk
 */
@Slf4j
@RestController
@RequestMapping("/web/department")
@CacheConfig(cacheNames = "department")
public class DepartmentController extends BaseController {

    @Autowired
    private ISysDepartmentService departmentService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleDepartmentService roleDepartmentService;

    @Autowired
    private ISysDepartmentHeaderService departmentHeaderService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private DepartmentManage departmentManage;
    /**
     * 通过id获取
     * @param parentId
     * @param openDataFilter
     * @return
     */
    @RequestMapping(value = "/getByParentId/{parentId}",method = RequestMethod.GET)
    public ApiResult getByParentId(@PathVariable String parentId,
                                   @RequestParam(required = false, defaultValue = "true")
                                           Boolean openDataFilter){

        List<SysDepartment> list = new ArrayList<>();
        SecUser secUser= SecurityUtils.getSecUser();
        SysUser u=userService.findByUsername(secUser.getUsername());
        String key = "department::"+parentId+":"+u.getId()+"_"+openDataFilter;
        String v = redisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(v)){
            list = JacksonUtil.from(v,new TypeReference<List<SysDepartment>>() {});
            return renderOk().add(list);
        }
        list = departmentManage.findByParentIdOrderBySortOrder(parentId, openDataFilter);
        list = setInfo(list);
        redisTemplate.opsForValue().set(key,
                JacksonUtil.to(list));
        return renderOk().add(list);
    }

    /**
     * 添加
     * @param department
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public ApiResult  add(@ModelAttribute SysDepartment department){

        departmentService.save(department);
        // 如果不是添加的一级 判断设置上级为父节点标识
        if(!CommonConstant.PARENT_ID.equals(department.getParentId())){
            SysDepartment parent = departmentService.getById(department.getParentId());
            if(parent.getIsParent()==null||!parent.getIsParent()){
                SysDepartment update=new SysDepartment();
                update.setId(parent.getId());
                update.setIsParent(true);
                departmentService.updateById(update);
            }
        }
        // 更新缓存
        Set<String> keys = redisTemplate.keys("department::*");
        redisTemplate.delete(keys);
        return renderOk("添加成功");
    }

    /**
     * 编辑
     * @param department
     * @param mainHeader
     * @param viceHeader
     * @return
     */
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public ApiResult edit(@ModelAttribute SysDepartment department,
                               @RequestParam(required = false) String[] mainHeader,
                               @RequestParam(required = false) String[] viceHeader){

         departmentService.updateById(department);
        // 先删除原数据
        departmentHeaderService.deleteByDepartmentId(department.getId());
        for(String id:mainHeader){
            SysDepartmentHeader dh = new SysDepartmentHeader();
            dh.setUserId(id);
            dh.setDepartmentId(department.getId());
            dh.setType(CommonConstant.HEADER_TYPE_MAIN);
            departmentHeaderService.save(dh);
        }
        for(String id:viceHeader){
            SysDepartmentHeader dh = new SysDepartmentHeader();
            dh.setUserId(id);
            dh.setDepartmentId(department.getId());
            dh.setType(CommonConstant.HEADER_TYPE_VICE);
            departmentHeaderService.save(dh);
        }
        // 手动删除所有部门缓存
        Set<String> keys = redisTemplate.keys("department:" + "*");
        redisTemplate.delete(keys);
        // 删除所有用户缓存
        Set<String> keysUser = redisTemplate.keys("user:" + "*");
        redisTemplate.delete(keysUser);
        return renderOk("编辑成功");
    }

    /**
     * 批量通过id删除
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delByIds/{ids}",method = RequestMethod.DELETE)
    public ApiResult delByIds(@PathVariable String[] ids){

        for(String id:ids){
            List<SysUser> list = userService.findByDepartmentId(id);
            if(list!=null&&list.size()>0){
                return renderError("删除失败，包含正被用户使用关联的部门");
            }
        }
        for(String id:ids){
            departmentService.removeById(id);
            // 删除关联数据权限
            roleDepartmentService.deleteByDepartmentId(id);
            // 删除关联部门负责人
            departmentHeaderService.deleteByDepartmentId(id);
        }
        // 手动删除所有部门缓存
        Set<String> keys = redisTemplate.keys("department:" + "*");
        redisTemplate.delete(keys);
        // 删除数据权限缓存
        Set<String> keysUserRoleData = redisTemplate.keys("userRole::depIds:" + "*");
        redisTemplate.delete(keysUserRoleData);
        return renderOk("批量通过id删除数据成功");
    }

    /**
     * 部门名模糊搜索
     * @param title
     * @param openDataFilter
     * @return
     */
    @RequestMapping(value = "/search",method = RequestMethod.GET)

    public ApiResult searchByTitle(@RequestParam String title,
                                   @RequestParam(required = false, defaultValue = "true") Boolean openDataFilter){

        List<SysDepartment> list = departmentManage.findByTitleLikeOrderBySortOrder(title, openDataFilter);
        list = setInfo(list);
        return renderOk().add(list);
    }

    public List<SysDepartment> setInfo(List<SysDepartment> list){

        // lambda表达式
        list.forEach(item -> {
            if(!CommonConstant.PARENT_ID.equals(item.getParentId())){
                SysDepartment parent = departmentService.getById(item.getParentId());
                item.setParentTitle(parent.getTitle());
            }else{
                item.setParentTitle("一级部门");
            }
            // 设置负责人
            item.setMainHeader(departmentHeaderService.findHeaderByDepartmentId(item.getId(), CommonConstant.HEADER_TYPE_MAIN));
            item.setViceHeader(departmentHeaderService.findHeaderByDepartmentId(item.getId(), CommonConstant.HEADER_TYPE_VICE));
        });
        return list;
    }
}
